Avoid `unwrap` when parsing lockfiles
authorAlex Crichton <alex@alexcrichton.com>
Wed, 4 Feb 2015 07:27:06 +0000 (23:27 -0800)
committerAlex Crichton <alex@alexcrichton.com>
Wed, 4 Feb 2015 07:27:06 +0000 (23:27 -0800)
Why not use `try!` instead!

Closes #1267

src/cargo/ops/lockfile.rs
tests/test_bad_config.rs

index 463d9467695524e786671aa2a82f80f00a1416dc..0180d9ce2b7113f72dd4df646471269cf773bc3c 100644 (file)
@@ -4,13 +4,15 @@ use rustc_serialize::{Encodable, Decodable};
 use toml::{self, Encoder, Value};
 
 use core::{Resolve, resolver, Package, SourceId};
-use util::CargoResult;
+use util::{CargoResult, ChainError, human};
 use util::toml as cargo_toml;
 
 pub fn load_pkg_lockfile(pkg: &Package) -> CargoResult<Option<Resolve>> {
     let lockfile = pkg.get_manifest_path().dir_path().join("Cargo.lock");
     let source_id = pkg.get_package_id().get_source_id();
-    load_lockfile(&lockfile, source_id)
+    load_lockfile(&lockfile, source_id).chain_error(|| {
+        human(format!("failed to parse lock file at: {}", lockfile.display()))
+    })
 }
 
 pub fn load_lockfile(path: &Path, sid: &SourceId) -> CargoResult<Option<Resolve>> {
@@ -24,7 +26,7 @@ pub fn load_lockfile(path: &Path, sid: &SourceId) -> CargoResult<Option<Resolve>
 
     let table = toml::Value::Table(try!(cargo_toml::parse(s.as_slice(), path)));
     let mut d = toml::Decoder::new(table);
-    let v: resolver::EncodableResolve = Decodable::decode(&mut d).unwrap();
+    let v: resolver::EncodableResolve = try!(Decodable::decode(&mut d));
     Ok(Some(try!(v.to_resolve(sid))))
 }
 
index 4597ae763f1511568de8cb8f0ff5ec9e85f8be1c..9b36fd586d6784091c33fd0e005adf64cef61479 100644 (file)
@@ -200,3 +200,23 @@ Caused by:
 
 "));
 });
+
+test!(bad_cargo_lock {
+    let foo = project("foo")
+    .file("Cargo.toml", r#"
+        [package]
+        name = "foo"
+        version = "0.0.0"
+        authors = []
+    "#)
+    .file("Cargo.lock", "")
+    .file("src/lib.rs", "");
+
+    assert_that(foo.cargo_process("build").arg("-v"),
+                execs().with_status(101).with_stderr("\
+failed to parse lock file at: [..]Cargo.lock
+
+Caused by:
+  expected a section for the key `root`
+"));
+});